<template>
  <div :class="goodClass" :style="style">
    <img :src="imgSrc" :alt="name" />
  </div>
</template>

<script lang="ts">
import classNames from "classnames";
import {
  defineComponent,
  computed,
  type PropType,
  type CSSProperties,
} from "vue";

// 动态导入所有图标文件
const iconModules = import.meta.glob(
  "@/assets/img/icons/*.{svg,png,jpg,jpeg,gif}",
  {
    eager: true,
    import: "default",
  }
);

export default defineComponent({
  name: "Icon",
  props: {
    name: {
      type: String as PropType<IconName>,
      required: true,
      validator: (value: string) => {
        // 简单的文件名格式验证（可选的）
        return /^[a-zA-Z0-9_-]+$/.test(value);
      },
    },
    class: {
      type: String,
      required: false,
    },
    style: {
      required: false,
      type: Object as PropType<CSSProperties>,
    },
  },
  setup(props) {
    const imgSrc = computed(() => {
      // 查找匹配的图片文件
      const matches = Object.entries(iconModules).find(([path]) => {
        const filename = path.split("/").pop()?.split(".")[0];
        return filename === props.name;
      });

      if (!matches) {
        console.warn(`Icon "${props.name}" not found in assets/img/icons`);
        return "";
      }

      return matches[1] as string;
    });

    const goodClass = computed(() => {
      return classNames("icon-box", props.class);
    });

    return { imgSrc, goodClass };
  },
});
</script>

<style lang="scss" scoped>
.icon-box {
  width: 28px;
  display: inline-block;
  height: 28px;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
